
package org.curl;

/**
 * This error is thrown whenever an unrecoverable error
 * occurs internally in CURL. The message text and error code 
 * provide a further description of the problem. The exception
 * has a <code>throwable</code> field which holds the underlying
 * throwable that caused the problem (if this information is
 * available (i.e. it may be null)).
 * 
 * @author s.e.t.i.
 */
public class CURLError extends Error {
    /**
     * The CURL error code, one of CURL.ERROR_*.
     */
	public int code;

	/**
	 * The underlying throwable that caused the problem,
	 * or null if this information is not available.
	 */
	public Throwable throwable;

	/**
	 * Constructs a new instance of this class with its 
	 * stack trace filled in. The error code is set to an
	 * unspecified value.
	 */
	public CURLError() {
		this(CURL.ERROR_UNSPECIFIED);
	}

	/**
	 * Constructs a new instance of this class with its 
	 * stack trace and message filled in. The error code is
	 * set to an unspecified value.
	 *
	 * @param message the detail message for the exception
	 */
	public CURLError(String message) {
		super(message);
	}

	/**
	 * Constructs a new instance of this class with its 
	 * stack trace and error code filled in.
	 *
	 * @param code the CURL error code
	 */
	public CURLError (int code) {
		this (code, CURL.findErrorText (code));
	}

	/**
	 * Constructs a new instance of this class with its 
	 * stack trace, error code and message filled in.
	 *
	 * @param code the CURL error code
	 * @param message the detail message for the exception
	 */
	public CURLError (int code, String message) {
		super (message);
		this.code = code;
	}
	
	/**
	 *  Returns the string describing this CURLError object.
	 *  <p>
	 *  It is combined with the message string of the Throwable
	 *  which caused this CURLError (if this information is available).
	 *  </p>
	 *  @return the error message string of this CURLError object
	 */
	public String getMessage() {
		if (throwable == null)
			return super.getMessage();
		else
			return super.getMessage() + " (" + throwable.toString() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
	}

	/**
	 * Outputs a printable representation of this error's
	 * stack trace on the standard error stream.
	 */
	public synchronized void printStackTrace() {
		super.printStackTrace();
		if (throwable != null) {
			System.err.println("*** Stack trace of contained error ***"); //$NON-NLS-1$
			throwable.printStackTrace();
		}
	}
}
